<template>
  <div class="articleinfo">
    <div class="articleinfo-header">
      <van-search
        v-model="value"
        show-action
        shape="round"
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>

      <van-tabs
        type="card"
        v-model="currentTab"
        @change="handleChangeTab"
      >
        <van-tab
          v-for="(item, index) in title"
          :key="index"
          :title="item"
        >
          <div v-if="goodsinfo.length>0">
            <van-card
              v-for="item in computedGoods"
              :key="item.goodsId"
              :price="item.sellingPrice"
              :desc="item.tag"
              :title="item.goodsName"
              :thumb="item.goodsCoverImg"
              @click="toProduct(item.goodsId)"
            />
          </div>

          <div v-else>
            <p class="van-list__finished-text">没有更多了</p>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import { getGoodsinfo } from '@/api/article'

export default {
  name: 'articleinfo',
  data() {
    return {
      value: '',
      goodsinfo: [],
      computedGoods: [],
      currentTab: 0,
      title: ['推荐', '新品', '价格']
    }
  },
  methods: {
    async onSearch() {
      console.log(this.value)
      if (this.value === '') {
        return false
      }
      const { data } = await getGoodsinfo({ value: this.value })
      this.goodsinfo = data
      this.computedGoods = JSON.parse(JSON.stringify(this.goodsinfo))
    },
    handleChangeTab() {
      const resultMap = {
        0: () => this.goodsinfo,
        // 可选链操作符( ?. )允许读取位于连接对象链深处的属性的值，而不必明确验证链中的每个引用是否有效
        1: () => this.computedGoods.sort((a, b) => a?.goodsId - b?.goodsId),
        2: () => this.computedGoods.sort((a, b) => b?.sellingPrice - a?.sellingPrice)
      }
      this.computedGoods = JSON.parse(JSON.stringify(resultMap[this.currentTab]()))
    },
    toProduct(id) {
      console.log(id)
      this.$router.push({
        name: 'xiangqin',
        params: {
          id: id
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.articleinfo {
  .articleinfo-header {
    .van-search__action {
      width: 35px;
      border-radius: 10px;
      margin: 0px 11px;
      text-align: center;
      color: #fff;
      background: #1baeae;
    }

    .van-card__title {
      width: 100%;
      font-size: 17px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .van-card__desc {
      font-size: 15px;
      color: #999;
      margin-top: 15px;
    }

    .van-card__content {
      margin-left: 20px;
      overflow: hidden;
    }

    .van-card__price {
      font-size: 18px;
      color: #1baeae;
    }

    .van-list__finished-text {
      color: #969799;
      font-size: 17px;
      text-align: center;
    }
  }
}
</style>
